package com.wpml.oss.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wpml.oss.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Objects;

/**
 * @description:
 * @author: wp
 * @date: 2019-09-02 10:43
 **/
@Service
@Slf4j
public class OssServiceImpl implements OssService {

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Override
    public String uploadFile(MultipartFile file) throws IOException {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();
        fileName =StrUtil.strBuilder()
                        .append(DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN))
                        .append("/")
                        .append(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT))
                        .append(StrUtil.subSuf(fileName, Objects.requireNonNull(fileName).lastIndexOf("."))).toString();
        DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT);
        ossClient.putObject(bucketName, fileName, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        String fileUrl = StrUtil.strBuilder().append("https://").append(bucketName).append(".").append(endpoint).append("/").append(fileName).toString();
        log.info("附件上传成功，附件地址 fileUrl = {}", fileUrl);
        return fileUrl;
    }

    public static void main(String[] args) {
        String fileName = "fileName.jpg";
        fileName =StrUtil.strBuilder()
                .append(DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN))
                .append("/")
                .append(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT))
                .append(StrUtil.subSuf(fileName, Objects.requireNonNull(fileName).lastIndexOf("."))).toString();
        System.out.println(fileName);

        // https://bucketName.endpoint/1.jpg
        System.out.println(StrUtil.strBuilder().append("https://").append("bucketName").append(".").append("endpoint").append("/").append("1.jpg").toString());
    }
}
